package com.rayo.accesscontrollercopy.module.setting;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.ybq.android.spinkit.SpinKitView;
import com.rayo.accesscontrollercopy.R;
import com.rayo.accesscontrollercopy.app.BaseFragment;
import com.rayo.accesscontrollercopy.config.GlobalVariables;
import com.rayo.accesscontrollercopy.model.db.bean.SiteData;
import com.rayo.accesscontrollercopy.model.db.dao.SiteDao;
import com.rayo.accesscontrollercopy.model.db.dao.SiteImpl;
import com.rayo.accesscontrollercopy.model.network.WebSocketHelp;
import com.rayo.accesscontrollercopy.model.service.NetworkData;
import com.rayo.accesscontrollercopy.module.setting.presenter.NetworkPresenter;
import com.rayo.accesscontrollercopy.module.setting.view.INetworkView;
import com.rayo.accesscontrollercopy.utils.FileUtils;
import com.rayo.accesscontrollercopy.utils.PreferencesUtils;
import com.rayo.accesscontrollercopy.utils.ToastUtils;

import java.io.File;

import static com.rayo.accesscontrollercopy.model.service.NetWorkService.EXTRA_DATA;

/**
 * Created by yanghaojie on 16/7/21.
 */
public class NetworkFragment extends BaseFragment implements INetworkView {
    private EditText mEdtServerIp, mEdtServerPort;
    private Button mBtnConnect, mBtnSave, mBtnUpdate, mBtnClean, mBtnAppUpdate;
    private LinearLayout llDB;
    private TextView mEdtServerDb;

    private NetworkPresenter presenter;

    private SpinKitView spinKitView;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_network;
    }

    @Override
    protected void setupViews() {
        mEdtServerIp = (EditText) rootView.findViewById(R.id.edit_server_ip);
        mEdtServerPort = (EditText) rootView.findViewById(R.id.edit_server_port);
        mBtnConnect = (Button) rootView.findViewById(R.id.btn_server_connect);
        mBtnConnect.setOnClickListener(this);
        mBtnSave = (Button) rootView.findViewById(R.id.btn_server_save);
        mBtnSave.setOnClickListener(this);
        mBtnUpdate = (Button) rootView.findViewById(R.id.btn_update_database);
        mBtnUpdate.setOnClickListener(this);
        mBtnAppUpdate = (Button) rootView.findViewById(R.id.btn_check_update);
        mBtnAppUpdate.setOnClickListener(this);
        mBtnClean = (Button) rootView.findViewById(R.id.btn_clean_cache);
        mBtnClean.setOnClickListener(this);
        spinKitView = (SpinKitView) rootView.findViewById(R.id.pb_network_loading);

        mEdtServerDb = (TextView)rootView.findViewById(R.id.tv_db);
        llDB = (LinearLayout)rootView.findViewById(R.id.ll_db);
        llDB.setOnClickListener(this);
        if ( PreferencesUtils.getBoolean(getActivity(), "isdbname")){
            mEdtServerDb.setText( PreferencesUtils.getString(getActivity(), "database"));
        }
    }

    @Override
    protected void initialized() {
        presenter = new NetworkPresenter(getContext(), this);
        presenter.initData();

        IntentFilter intentFilter = new IntentFilter();

        // 2. 设置接收广播的类型
        intentFilter.addAction("CONNECTIVITY_CHANGE");
        intentFilter.addAction("Error");
        // 3. 动态注册：调用Context的registerReceiver（）方法
        getActivity().registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    public void onPause() {
        super.onPause();
        presenter.onDestroy();
        getActivity().unregisterReceiver(broadcastReceiver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_server_connect:
                presenter.testServer();
                break;
            case R.id.btn_server_save:
                if (TextUtils.isEmpty(mEdtServerIp.getText())||TextUtils.isEmpty(mEdtServerPort.getText())){

                    ToastUtils.showShortToast(getActivity(),getString(R.string.ip_null));
                    return;

                }
                presenter.saveServer();
                break;
            case R.id.btn_update_database:
                presenter.updateDb();
                break;
            case R.id.btn_clean_cache:
                presenter.cleanCache();
                break;
            case R.id.btn_check_update:
                presenter.checkUpdate();
                break;
            case R.id.ll_db:
                presenter.testServer();
                final EditText et = new EditText(getActivity());
                et.setInputType(EditorInfo.TYPE_CLASS_NUMBER );
                new AlertDialog.Builder(getContext()).setTitle(R.string.databasecode).setView(et)
                        .setIcon(R.drawable.database).setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PreferencesUtils.putBoolean(getActivity(),"isFirst",false);
                        PreferencesUtils.putBoolean(getActivity(), "isdbname", false);
                        presenter.cleanCache();

                        WebSocketHelp.getmInstance().getDb(et.getText().toString().trim());
//                        hintKeyboard();
                    }
                }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).show();
                break;
            default:
                break;
        }
    }

    @Override
    public void showProgressBar(boolean isShow) {
        if (isShow) spinKitView.setVisibility(View.VISIBLE);
        else spinKitView.setVisibility(View.GONE);
    }

    @Override
    public void showSnackBar(String txt) {
        if (null != txt && null != rootView) showShortSnackbar(rootView, txt, null);
    }

    @Override
    public void showAlertDialog(String txt) {
        if (null != txt)
            new AlertDialog.Builder(getContext()).setTitle(R.string.app_name).setMessage(txt)
                    .setIcon(R.mipmap.ic_launcher).setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
    }

    @Override
    public String getServerIp() {
        if (null == mEdtServerIp) return null;
        return mEdtServerIp.getText().toString().trim();
    }

    @Override
    public String getServerPort() {
        if (null == mEdtServerPort) return null;
        return mEdtServerPort.getText().toString().trim();
    }

    @Override
    public void setServerInfo(String ip, String port) {
        if (null != ip) mEdtServerIp.setText(ip);
        if (null != port) mEdtServerPort.setText(port);
    }

    @Override
    public void isInstall(final File file) {
//        final File file = FileUtils.saveFile(source, WebSocketHelp.getmInstance().getAppVersion() + ".apk");
        if (null == file) {
            showSnackBar(getString(R.string.update_failed));
            return;
        }
        new AlertDialog.Builder(getContext()).setTitle(R.string.app_name).setMessage(R.string.update)
                .setIcon(R.mipmap.ic_launcher).setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                FileUtils.installApp(file, getContext());
            }
        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).show();
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("CONNECTIVITY_CHANGE")) {
                String name = intent.getStringExtra("name");
                mEdtServerDb.setText(name);
                PreferencesUtils.putBoolean(getActivity(), "isdbname", true);
                PreferencesUtils.putString(getActivity(), "database", name);
                Toast.makeText(getActivity(), "获取数据库版本成功", Toast.LENGTH_SHORT).show();
                SiteDao siteDao = new SiteImpl();
                SiteData siteData = siteDao.findFirst();
                siteData.setSite(name);
                siteDao.updateSite(siteData);
                GlobalVariables.getInstance().setmSiteData(siteData);
            }else if (action.equals("Error")){
                NetworkData networkData = (NetworkData) intent.getSerializableExtra(EXTRA_DATA);
                Toast.makeText(getActivity(),(String)networkData.getData(),Toast.LENGTH_SHORT).show();
            }
        }
    };
}
